大家好,上一篇我們成功在Android手機上接到通知,今天我們在底部導航欄上顯示通知
先設置一個變數
int notificationCount = 0;
從前篇我們可以看到如果App是打開的狀態,消息會透過onMessage傳進來,所以我在這邊做加一的動作
I/flutter (18142): onMessage: {notification: {title: 再測試一次, body: 測試2}, data: {data: 來自星星的你, type: 最新上線}}
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
@override
void initState() {
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
setState(() => notificationCount++); //新增,接收到訊息就+1
// _showItemDialog(message);
},
onBackgroundMessage: myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
// _navigateToItemDetail(message);
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
// _navigateToItemDetail(message);
},
);
super.initState();
}
修改BottomNavigationBarItem
,原本只有一個Icon
,改成再用Stack
疊一個數字上去
_buildItemWithNotification() {
return Stack(
children: [
Icon(Icons.featured_play_list),
if( notificationCount!=0 ) Positioned( //判斷假如不是零的時候才顯示
top: 0,
right: 0,
child: Transform.translate(
offset: Offset(3,-3), //先右上偏移一點點
child: Container(
padding: EdgeInsets.all(1),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(6),
),
constraints: BoxConstraints(
minWidth: 12,
minHeight: 12,
),
child: Text('$notificationCount',style: TextStyle(fontSize: 10.0),textAlign: TextAlign.center,),
),
),
)
],
);
}
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("首頁")),
BottomNavigationBarItem(
icon: Icon(Icons.search), title: Text("搜尋")),
BottomNavigationBarItem(
icon: _buildItemWithNotification(), title: Text("即將上線")),
BottomNavigationBarItem(
icon: Icon(Icons.file_download), title: Text("下載內容")),
BottomNavigationBarItem(
icon: Icon(Icons.more_vert), title: Text("更多")),
],
iconSize: 24.0,
backgroundColor: Colors.black54,
currentIndex: currentIndex,
selectedFontSize: 12.0,
unselectedFontSize: 12.0,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.grey,
onTap: (index) {
setState(() {
currentIndex = index;
});
},
type: BottomNavigationBarType.fixed,
),
GitHub連結: flutter-netflix-clone